package com.cyou.nad.datastore.query.dialect;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.jdbc.datasource.DataSourceUtils;
//为了适用不同的数据库---lee
public class DialectFactory {
	private final static Oracle9iDialect oracle9iDialect = new Oracle9iDialect();
	private final static MySqlDialect mySqlDialect = new MySqlDialect();
	private final static Map<DataSource, Dialect> databaseProduct = new HashMap<DataSource, Dialect>();

	public static Dialect getDialect(DataSource dataSource) {
		Dialect ret = databaseProduct.get(dataSource);
		if (ret != null)
			return ret;

		Connection connection = DataSourceUtils.getConnection(dataSource);
		String product = "";
		try {
			product = connection.getMetaData().getDatabaseProductName();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DataSourceUtils.releaseConnection(connection, dataSource);
		}

		if (product.toLowerCase().indexOf("oracle") != -1) {
			ret = oracle9iDialect;
		} else if (product.toLowerCase().indexOf("mysql") != -1) {
			ret = mySqlDialect;
		} else {
			throw new IllegalArgumentException("不能判断数据库类型，dialect：" + product + "\t dataSource:" + dataSource);
		}
		databaseProduct.put(dataSource, ret);
		return ret;
	}
}
